﻿using System.Text;

namespace CommonUtils
{
    /// <summary>
    /// 文本编码补充
    /// 不要使用Encoding.Default，Encoding.Default会随着操作系统变化
    /// default = null
    /// </summary>
    public static class TextEncoding
    {
        /// <summary>
        /// Framework环境不需要RegisterProvider，如果一定要RegisterProvider，项目需直接引用nuget:System.Text.Encoding.CodePages,否则会引发dll缺失报错
        /// </summary>
        static TextEncoding()
        {
            Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
            //LogUtil.Info("RegisterCodePagesEncodingProvider!");
        }

        private static Encoding _gb2312;

        /// <summary>
        ///  Core环境需要RegisterProvider，Framework环境不需要
        /// </summary>
        [Warning("Core环境需要RegisterProvider，Framework环境不需要")]
        public static Encoding GB2312
        {
            get
            {
                if (_gb2312 == default)
                    _gb2312 = Encoding.GetEncoding(936);

                return _gb2312;
            }
        }

        /// <summary>
        ///  Core环境需要RegisterProvider，Framework环境不需要
        /// </summary>
        [Warning("Core环境需要RegisterProvider，Framework环境不需要")]
        public static Encoding GBK => GB2312;

        public static Encoding UTF8 { get; } = Encoding.UTF8;

        public static Encoding UTF8Bom { get; } = new UTF8Encoding(true);

        public static Encoding UTF8NoBom { get; } = new UTF8Encoding(false);

        /// <summary>
        /// 0xEF, 0xBB, 0xBF 239, 187, 191
        /// </summary>
        public static byte[] UTF8BomBytes { get; } = { 0xEF, 0xBB, 0xBF };

        public static string UTF8BomString { get; } = UTF8Bom.GetString(UTF8BomBytes);

        public static Encoding Null2utf8(this Encoding encoding)
        => encoding ?? UTF8;
    }
}
